package code.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bson.util.StringRangeSet;

import com.gargoylesoftware.htmlunit.Cache;

import code.util.RequestExecuteThread;

public class UrlFilterWithMap implements Filter {
    ConcurrentLinkedQueue<Map<String, ?>> requestQueue = new ConcurrentLinkedQueue<Map<String, ?>>();
    ConcurrentHashMap<String, Boolean> flagMap = new ConcurrentHashMap<String, Boolean>();

    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

        System.out.println(filterConfig.getInitParameter("redirectURL"));
        System.out.println(filterConfig.getInitParameter("checkSessionKey"));
        new Thread(new RequestExecuteThread(requestQueue, flagMap)).start();
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest req = (HttpServletRequest) request;
//        System.out.println(req.getRequestURI());
//        System.out.println(req.getRequestURL());
//        System.out.println(req.getAttribute("id"));
//        System.out.println(req.getContextPath());
        HttpServletResponse resp = (HttpServletResponse) response;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("request", req);
        map.put("response", resp);
        map.put("filterChain", chain);
        String requestFlag = req.getRequestURI() + System.currentTimeMillis() + new Random().nextLong();
        map.put("flag", requestFlag);
        requestQueue.add(map);
        Set<String> sets = flagMap.keySet();
        System.out.println(sets.size());
        flagMap.put(requestFlag, false);
        while (true) {
            if (flagMap.get(requestFlag) == true) {
                flagMap.remove(requestFlag);
                break;
            }
        }
        // if ("/filter/user/getUser".equals(req.getRequestURI())) {
        // resp.sendRedirect("http://www.baidu.com");
        // return;
        // } else if ("/filter/user/getUser1".equals(req.getRequestURI())) {
        // req.getRequestDispatcher("/user/getUser").forward(req, resp);
        // return;
        // }
        // System.out.println(req.getRequestURI());
        // chain.doFilter(request, response);
    }

    public void destroy() {
        // TODO Auto-generated method stub

    }

}
